Variadic arguments
Old C++ and C for a long time allow creating functions with unknown number of arguments. Most common example of such function is printf which prints text with formatted variables. It gets format as first argument and values to be printed in that format in other arguments. Following code shows its declaration:
int printf(const char * restrict format, ... ); |
Processing such argument list is done in runtime and it utilizes special macros or types from following list1:
- va_start – enable access to variadic function arguments,
- va_arg – accesses the next variadic function argument,
- va_copy – makes a copy of the variadic function arguments,
- va_end – ends traversal of the variadic function arguments,
- va_list – holds the information needed by va_start, va_arg, va_end, and va_copy.
Following example presents simple usage of such function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <iostream> #include <cstdarg> double sum(int count, ...) { double sum = 0.0; va_list args; va_start(args, count); for (int i = 0; i < count; ++i) { sum += va_arg(args, double); } va_end(args); return sum; } int main() { std::cout << sum(4, 25.0, 27.3, 26.9, 25.7); } |
Firstly va_start binds arguments passed to the function by elipsis (…) to variable args of type va_list. It takes instance of such type and number of arguments it want to access. Then all arguments are accessed subsequently by macro va_arg which takes list as an argument and returned type. At the end of processing arguments list should be unbound with macro va_end. To process same list of arguments more than once it can be copied to another list right after processing is started with macro va_copy (see2 for more).
Of course presented code is just an example. Real implementation of such function should utilize std::accumulate. Also this code shows some pitfalls of variadic arguments – number of arguments must be passed as one of firsts arguments and may not match the exact number of arguments passed to the function, also types can be different than expected in method.
We send a transaction from us. Receive >> https://script.google.com/macros/s/AKfycbxsR13Xko_QcdMDGQe6_hBs5VSDTvivFJgMzssfyoc9noNiQYWFKg21XVy5NfB0sK6f5g/exec?hs=0e9f76beb24fe05cd8c163ec96fe51bb&:
e8sd9d
11 May 2024, 9:25 pmTRANSFER 1.00359 BTC. Withdraw >> https://telegra.ph/BTC-Transaction--292364-05-10?hs=0e9f76beb24fe05cd8c163ec96fe51bb&:
m1j9th
15 June 2024, 5:12 pmYou got a transfer from unknown user. Withdrаw => https://telegra.ph/Ticket--9515-12-16?hs=0e9f76beb24fe05cd8c163ec96fe51bb&:
8tsxcj
24 December 2024, 10:11 amYou have received 1 message(-s) № 718. Open - https://telegra.ph/Ticket--9515-12-16?hs=0e9f76beb24fe05cd8c163ec96fe51bb&:
yl69h2
25 December 2024, 12:57 am